package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.commonutils.ResultCode;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.vo.OneSubject;
import com.atguigu.eduservice.entity.vo.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author fly
 * @since 2021-09-20
 */
@Service
@Slf4j
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    /**
     * 添加课程分类
     */
    @Override
    public void saveSubject(MultipartFile file) {
        try {
            InputStream input = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(input, SubjectData.class, new SubjectExcelListener(this))
                    .sheet()
                    .doRead();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new GuliException(ResultCode.ERROR, "添加课程分类失败");
        }
    }

    /**
     * 课程分类列表（树形）
     */
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        List<EduSubject> allSubjectList = this.list(null);
        // 一级分类
        List<OneSubject> oneSubjectList = allSubjectList.stream()
                .filter(e -> StringUtils.equals("0", e.getParentId()))
                // EduSubject转OneSubject，这里使用第一种方式：eanUtils.copyProperties
                .map(e -> {
                    OneSubject oneSubject = new OneSubject();
                    BeanUtils.copyProperties(e, oneSubject);
                    return oneSubject;
                })
                .collect(Collectors.toList());
        // 查找每个一级分类下的二级分类
        for (OneSubject e1 : oneSubjectList) {
            List<TwoSubject> twoSubjectList = allSubjectList.stream()
                    .filter(e2 -> StringUtils.equals(e1.getId(), e2.getParentId()))
                    // EduSubject转TwoSubject，这里使用第二种方式：手动创建对象并赋值
                    .map(e -> TwoSubject.builder().id(e.getId()).title(e.getTitle()).build())
                    .collect(Collectors.toList());
            // 将二级分类封装进一级分类
            e1.setChildren(twoSubjectList);
        }
        return oneSubjectList;
    }
}
